﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PipeAuto.DAL;
using PipeAuto.DAL.PipeAutoDataSetTableAdapters;
using System.Threading;
using WinformAuthentication;
using System.Data.SqlClient;
using System.IO;
using OpenNETCF.Desktop.Communication;
using Arthasliu.Uti;

namespace PipeAuto.MgrPlatform
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();

            if (Properties.Settings.Default.Maxmium == true)
            {
                this.WindowState = FormWindowState.Maximized;
            }
            else
            {
                this.Width = Properties.Settings.Default.Width;
                this.Height = Properties.Settings.Default.Height;
            }

            this.barcodeEleComboBox.SelectedIndex = 0;

            //initial enabled barcode element table
            for (int i = 0; i < this.eleEnabledEleTable.Length; i++)
            {
                this.eleEnabledEleTable[i] = new PipeAutoDataSet.BarcodeElementDicDataTable();
            }

            newStockOutDataGridView.AutoGenerateColumns = false;
            soSearchDataGridView.AutoGenerateColumns = false;

            
        }



        #region Properties

        /// <summary>
        /// user's department link label
        /// </summary>
        public LinkLabel UserDeptLinkLabel
        {
            get
            {
                return this.deptLinkLabel;
            }
        }

        #endregion


        #region DateField

        /// <summary>
        /// record operation state
        /// </summary>
        private MgrPlatformGlobal.OperationState opState = MgrPlatformGlobal.OperationState.Null;

        /// <summary>
        /// barcode elements source table for rule binding source
        /// </summary>
        private PipeAutoDataSet.BarcodeElementDicDataTable[] eleEnabledEleTable = new PipeAutoDataSet.BarcodeElementDicDataTable[4];


        private const string successfulMsg = "成功！";

        private const string failureMsg = "未知错误，请联系管理员！";

        private const string delConfirmMsg = "是否继续？";

        private const string redundantTitleMsg = "名称重复，请检查！";

        private const string confirmCaption = "确认";


        /// <summary>
        /// whether rule related controls has binded binding source
        /// </summary>
        //private bool ruleBindedFlag = false;

        /// <summary>
        /// whether the barcode element combobox's selectedindexchanged event has been subscribed
        /// </summary>
        //private bool eleCmbBoxSelectedIndexChangedSubscribed = false;


        #endregion

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void barcodeEletabPage_Enter(object sender, EventArgs e)
        {

            

        }

        private void barcodeEleComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            PipeAutoDataSet.BarcodeElementDicDataTable myTable = new PipeAutoDataSet.BarcodeElementDicDataTable();

#if !DEBUG
            try
            {
#endif
                DAL.PipeAutoDataSetTableAdapters.BarcodeElementDicTableAdapter myAdapter = new DAL.PipeAutoDataSetTableAdapters.BarcodeElementDicTableAdapter();
                myAdapter.FillByType(myTable, this.barcodeEleComboBox.SelectedIndex + 1);
#if !DEBUG
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
#endif

            barcodeEleToolBtnListViewer.InnerListViewer.Items.Clear();

            if (myTable.Count != 0)
            {
                foreach (var myRow in myTable)
                {
                    string myComment = string.Empty;

                    //avoid null
                    try
                    {
                        myComment = myRow.Comment;
                    }
                    catch (System.Exception)
                    {
                    	
                    }

                    //insert into listview
                    InsertNewEleItem(myRow.ID,myRow.Title,myRow.State,myRow.Code,myRow.PinYinCode,myComment);
                }
            }
        }

        private void InsertNewEleItem(string id,string title,int state,string code,string pinyinCode,string comment)
        {
            ListViewItem myItem = new ListViewItem { Text = title, Tag = id };
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "state", Text = state == 1 ? "启用" : "停用", Tag = state });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "code", Tag = code });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "pycode", Tag = pinyinCode });
            string myComment = string.Empty;


            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "comment", Tag = comment });

            this.barcodeEleToolBtnListViewer.InnerListViewer.Items.Add(myItem);
        }

        private void barcodeEleToolBtnListViewer_InnerListViewSelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.barcodeEleToolBtnListViewer.InnerListViewer.SelectedItems.Count==0)
            {
                return;
            }

            var mySelectedItem=this.barcodeEleToolBtnListViewer.InnerListViewer.SelectedItems[0];

            this.eleTitleTextBox.Text = mySelectedItem.Text;
            this.eleCodeTextBox.Text = (string)mySelectedItem.SubItems["code"].Tag;
            this.eleDisableCheckBox.Checked = ((int)mySelectedItem.SubItems["state"].Tag) == 1 ? false : true;
            this.eleCommentTextBox.Text=(string)mySelectedItem.SubItems["comment"].Tag;
            elePyCodeTextBox.Text = (string)mySelectedItem.SubItems["pycode"].Tag;
        }

        private void barcodeEleToolBtnListViewer_NewBtnClick(object sender, EventArgs e)
        {
            this.barcodeEleSplitContainer.Panel2.Enabled = true;
            this.barcodeEleSplitContainer.Panel1.Enabled = false;

            //clean control
            this.eleTitleTextBox.Text = string.Empty;
            this.eleCodeTextBox.Text = string.Empty;
            this.eleDisableCheckBox.Checked = false;
            this.eleCommentTextBox.Text = string.Empty;
            this.eleTitleTextBox.Enabled = true;

            this.opState = MgrPlatformGlobal.OperationState.Add;
        }

        private void eleCancelButton_Click(object sender, EventArgs e)
        {
            this.barcodeEleSplitContainer.Panel2.Enabled = false;
            //this.barcodeEleToolBtnListViewer.Enabled = true;
            this.barcodeEleSplitContainer.Panel1.Enabled = true;

        }

        
        private void barcodeEleToolBtnListViewer_UpdateBtnClick(object sender, EventArgs e)
        {
            this.barcodeEleSplitContainer.Panel2.Enabled = true;
            this.barcodeEleSplitContainer.Panel1.Enabled = false;
            this.opState = MgrPlatformGlobal.OperationState.Update;
            //this.eleTitleTextBox.Enabled = false;
        }

        private void barcodeEleToolBtnListViewer_DelBtnClick(object sender, EventArgs e)
        {
            if (MessageBox.Show(delConfirmMsg,"确认", MessageBoxButtons.YesNo)!=DialogResult.Yes)
            {
                return;
            }

            //element id
            string myEleID = (string)this.barcodeEleToolBtnListViewer.SelectedItems[0].Tag;


            try
            {
                BarcodeElementDicTableAdapter myAdapter = new BarcodeElementDicTableAdapter();
                myAdapter.DeleteQuery(myEleID);
                this.barcodeEleToolBtnListViewer.SelectedItems[0].Remove();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
           
            MessageBox.Show("成功！");
        }

        private void eleSaveButton_Click(object sender, EventArgs e)
        {
            if (eleTitleTextBox.Text.Trim()==string.Empty)
            {
                MessageBox.Show("名称不能为空！");
                return;
            }

            if (eleCodeTextBox.Text.Trim()==string.Empty)
            {
                MessageBox.Show("代码不能为空！");
                return;
            }

            if (elePyCodeTextBox.Text.Length!=eleTitleTextBox.Text.Length)
            {
                if (MessageBox.Show("拼音码不完整，是否继续？",confirmCaption,MessageBoxButtons.YesNo)!=DialogResult.Yes)
                {
                    return;
                }
            }

            string myCode = eleCodeTextBox.Text.ToUpper();

            switch(this.opState)
            {
                case MgrPlatformGlobal.OperationState.Add:
                    {
                        string myID = Guid.NewGuid().ToString();
                        

                        //add to db
                        try
                        {
                            BarcodeElementDicTableAdapter myAdapter = new BarcodeElementDicTableAdapter();
                            

                            if (myAdapter.ScalarByTitle(eleTitleTextBox.Text) > 0)
                            {
                                MessageBox.Show(redundantTitleMsg);
                                return;
                            }

                            if (myAdapter.ScalarByCode(eleCodeTextBox.Text) > 0)
                            {
                                MessageBox.Show("代码重复，请检查！");
                                return;
                            }
                            myAdapter.InsertQuery(myID, eleTitleTextBox.Text, myCode,elePyCodeTextBox.Text, barcodeEleComboBox.SelectedIndex + 1, eleCommentTextBox.Text, eleDisableCheckBox.Checked == true ? 2 : 1);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }

                        //add to list
                        this.InsertNewEleItem(myID, eleTitleTextBox.Text, this.eleDisableCheckBox.Checked == true ? 2 : 1, myCode,elePyCodeTextBox.Text, eleCommentTextBox.Text);

                        break; 
                    }
                case MgrPlatformGlobal.OperationState.Update:
                    {
                        try
                        {
                            var myItem=this.barcodeEleToolBtnListViewer.SelectedItems[0];

                           

                            //update to db
                            BarcodeElementDicTableAdapter myAdapter = new BarcodeElementDicTableAdapter();

                            //need to check title unique
                            if (this.eleTitleTextBox.Text != myItem.Text)
                            {
                                if (myAdapter.ScalarByTitle(eleTitleTextBox.Text)>0)
                                {
                                    MessageBox.Show(redundantTitleMsg);
                                    return;
                                }
                            }

                            //need to check code unique
                            if (eleCodeTextBox.Text!=myItem.SubItems["code"].Tag as string)
                            {
                                if (myAdapter.ScalarByCode(eleCodeTextBox.Text)>0)
                                {
                                    MessageBox.Show("代码重复，请检查！");
                                    return;
                                }
                            }

                            myAdapter.UpdateQuery( eleTitleTextBox.Text,myCode,elePyCodeTextBox.Text, this.barcodeEleComboBox.SelectedIndex + 1, eleCommentTextBox.Text, eleDisableCheckBox.Checked == true ? 2 : 1, (string)myItem.Tag);

                            //update listview
                            myItem.Text = eleTitleTextBox.Text;
                            myItem.SubItems["code"].Tag = myCode;
                            myItem.SubItems["comment"].Tag = eleCommentTextBox.Text;
                            myItem.SubItems["state"].Text = eleDisableCheckBox.Checked == true ? "停用" : "启用";
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }
                        break;
                    }
                    default:
                    {
                        MessageBox.Show(failureMsg);
                        return;
                    }
            }

            this.opState = MgrPlatformGlobal.OperationState.Null;
            this.barcodeEleSplitContainer.Panel2.Enabled = false;
            this.barcodeEleSplitContainer.Panel1.Enabled = true;

            MessageBox.Show(successfulMsg);
        }

        private void barcodeRuleTabPage_Enter(object sender, EventArgs e)
        {

#if !DEBUG
            try
            {
#endif
                BarcodeElementDicTableAdapter myAdapter = new BarcodeElementDicTableAdapter();

                //fill data source table
                //for (int i = 0; i < this.eleEnabledEleTable.Length;i++ )
                //{
                //    myAdapter.FillByTypeState(this.eleEnabledEleTable[i], i + 1, 1);
                //}

                this.bindingComboboxDataSource(ruleCateComboBox, new BindingSource(), myAdapter.GetDataByTypeState(1, 1));
                this.bindingComboboxDataSource(ruleTradeComboBox, new BindingSource(), myAdapter.GetDataByTypeState(2, 1));
                this.bindingComboboxDataSource(rulePnComboBox, new BindingSource(), myAdapter.GetDataByTypeState(3, 1));
                this.bindingComboboxDataSource(ruleColorComboBox, new BindingSource(), myAdapter.GetDataByTypeState(4, 1));

#if !DEBUG
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
#endif

            //config binding setting once
            //if (this.ruleBindedFlag==false)
            //{
                
            //}


            PipeAutoDataSet.StockDataTable myTable = new PipeAutoDataSet.StockDataTable();

            try
            {
                StockTableAdapter myRuleAdapter= new StockTableAdapter();

                //fill binding source table

                myRuleAdapter.Fill(myTable);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message)	;
                return;
            }

            this.ruleToolBtnListViewer.InnerListViewer.Items.Clear();

            if (myTable.Count>0)
            {
                foreach (var myRow in myTable)
                {
                    this.inserNewRuleItem(myRow.ID, myRow.Title, myRow.CateCode, myRow.TradeCode, myRow.PnCode, myRow.ColorCode, myRow.State);
                }
            }
        }

        private void NewStockOutModel()
        {

            combSearchFlowLayoutPanel.Visible = false;
            setToolStripItemState(newStockOutToolStripButton);
            setToolStripItemState(voidSOToolStripButton);
            setToolStripItemState(financialToolStripButton);
            querySOToolStripButton.Enabled = false;
            soStateTitledComboBox.Visible = false;
            soDateSpanPanel.Visible = false;
            soQuantityPanel.Visible = true;
            soOpMethodTitledComboBox.Visible = false;
            soFinancialCancelToolStripButton.Enabled = false;
            soSendToolStripButton.Enabled = false;
            soAutoToolStripButton.Enabled = false;
            soDetailToolStripButton.Enabled = false;

            //hide check box
            soCateTitledComboBox.CheckBox = false;
            soTradeTitledComboBox.CheckBox = false;
            soPnTitledComboBox.CheckBox = false;
            soColorTitledComboBox.CheckBox = false;

            
        }

        private void QueryStockOutModel()
        {
            combSearchFlowLayoutPanel.Visible = true;
            newStockOutToolStripButton.Enabled = false;
            voidSOToolStripButton.Enabled = false;
            financialToolStripButton.Enabled = false;
            querySOToolStripButton.Enabled = true;
            soStateTitledComboBox.Visible = true;
            soDateSpanPanel.Visible = true;
            soQuantityPanel.Visible = false;
            soPnTitledComboBox.Visible = false;
            soColorTitledComboBox.Visible = false;
            soOpMethodTitledComboBox.Visible = true;
            soOpMethodTitledComboBox.CheckBox = true;
            setToolStripItemState(soFinancialCancelToolStripButton);
            setToolStripItemState(soSendToolStripButton);
            setToolStripItemState(soAutoToolStripButton);
            setToolStripItemState(soDetailToolStripButton);

            //display check box
            soStateTitledComboBox.CheckBox = true;
            soCateTitledComboBox.CheckBox = true;
            soTradeTitledComboBox.CheckBox = true;
            soPnTitledTextBox.CheckBox = true;
            //soColorTitledComboBox.CheckBox = true;
            soColorTitledTextBox.CheckBox = true;

        }

        private void setToolStripItemState(ToolStripItem control)
        {
            var myPrincipal = Thread.CurrentPrincipal;

            if (myPrincipal.IsInRole(control.Tag.ToString())==true)
            {
                control.Enabled = true;
            }
            else
            {
                control.Enabled = false;
            }
        }

        private void bindingComboboxDataSource(ComboBox cmbBox,BindingSource bindingSource,DataTable sourceTable,string filter="")
        {
            //recycle
            if (bindingSource.DataSource!=null)
            {
                var myTable = bindingSource.DataSource as DataTable;
                myTable.Clear();
            }

            cmbBox.DataSource = bindingSource;
            bindingSource.DataSource = sourceTable;
            bindingSource.Filter = filter;
            //bindingSource.ResetBindings(false);
            cmbBox.DataSource = bindingSource;
            cmbBox.DisplayMember = "title";
            cmbBox.ValueMember = "code";
            
        }

        private void inserNewRuleItem(string id, string title, string cate, string trade, string pn, string color, int state)
        {
            ListViewItem myItem = new ListViewItem { Text = title, Tag = id };
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name="state", Text = (state == 1 ? "启用" : "停用"), Tag = state });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "cate", Tag = cate });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "pn", Tag = pn });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "color", Tag = color });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "trade", Tag = trade });

            this.ruleToolBtnListViewer.InnerListViewer.Items.Add(myItem);
        }

        private void ruleToolBtnListViewer_NewBtnClick(object sender, EventArgs e)
        {
            this.ruleTitleTextBox.Text = this.generateBarcodeTitle();
            this.ruleDisableCheckBox.Checked = false;
            this.opState = MgrPlatformGlobal.OperationState.Add;

            this.ruleSplitContainer.Panel2.Enabled = true;
            this.ruleSplitContainer.Panel1.Enabled = false;

            
            //this.ruleTitleTextBox.Enabled = true;
        }

        private void ruleCancelButton_Click(object sender, EventArgs e)
        {
            this.opState = MgrPlatformGlobal.OperationState.Null;
            this.ruleSplitContainer.Panel2.Enabled = false;
            this.ruleSplitContainer.Panel1.Enabled = true;
        }

        private void ruleSaveButton_Click(object sender, EventArgs e)
        {
            if (this.ruleTitleTextBox.Text.Trim()==string.Empty)
            {
                MessageBox.Show("请填写名称！");
                return;
            }


            int myRuleEnable = ruleDisableCheckBox.Checked == true ? 2 : 1;

            switch (this.opState)
            {
                case MgrPlatformGlobal.OperationState.Add:
                    {
                        try
                        {
                            StockTableAdapter myAdapter = new StockTableAdapter();

                            //if (myAdapter.ScalarByTitle(this.ruleTitleTextBox.Text) > 0)
                            //{
                            //    MessageBox.Show("名称重复");
                            //    return;
                            //}

                            if (myAdapter.ScalarByCombination(this.ruleCateComboBox.SelectedValue as string, this.rulePnComboBox.SelectedValue as string, this.ruleTradeComboBox.SelectedValue as string, this.ruleColorComboBox.SelectedValue as string) > 0)
                            {
                                MessageBox.Show("条码规则重复");
                                return;
                            }

                            string myId=Guid.NewGuid().ToString();

                            myAdapter.InsertQuery(myId, ruleCateComboBox.SelectedValue.ToString(), ruleTradeComboBox.SelectedValue.ToString(), rulePnComboBox.SelectedValue.ToString(), ruleColorComboBox.SelectedValue.ToString(),myRuleEnable);

                            this.inserNewRuleItem(myId, ruleTitleTextBox.Text, ruleCateComboBox.SelectedValue.ToString(), ruleTradeComboBox.SelectedValue.ToString(), rulePnComboBox.SelectedValue.ToString(), ruleColorComboBox.SelectedValue.ToString(), myRuleEnable);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }
                        break;
                    }
                case MgrPlatformGlobal.OperationState.Update:
                        {
                            try
                            {
                                StockTableAdapter myAdapter= new StockTableAdapter();
                                myAdapter.UpdateRule(this.ruleCateComboBox.SelectedValue.ToString(), ruleTradeComboBox.SelectedValue.ToString(), rulePnComboBox.SelectedValue.ToString(), ruleColorComboBox.SelectedValue.ToString(),myRuleEnable, ruleToolBtnListViewer.SelectedItems[0].Tag.ToString());

                                var myItem = this.ruleToolBtnListViewer.SelectedItems[0];
                                myItem.Text = this.ruleTitleTextBox.Text;
                                myItem.SubItems["cate"].Tag = this.ruleCateComboBox.SelectedValue;
                                myItem.SubItems["trade"].Tag = this.ruleTradeComboBox.SelectedValue;
                                myItem.SubItems["pn"].Tag = this.rulePnComboBox.SelectedValue;
                                myItem.SubItems["color"].Tag = this.ruleColorComboBox.SelectedValue;
                                myItem.SubItems["state"].Text = myRuleEnable == 1 ? "启用" : "停用";
                                myItem.SubItems["state"].Tag = myRuleEnable;
                            }
                            catch (System.Exception ex)
                            {
                            	MessageBox.Show(ex.Message);
                                return;
                            }
                            break;
                        }
                    default:
                    {
                        MessageBox.Show(failureMsg);
                        return;
                    }
            }

            MessageBox.Show(successfulMsg);
            this.opState = MgrPlatformGlobal.OperationState.Null;
            this.ruleSplitContainer.Panel1.Enabled = true;
            this.ruleSplitContainer.Panel2.Enabled = false;
        }

        private void ruleToolBtnListViewer_UpdateBtnClick(object sender, EventArgs e)
        {
            this.opState = MgrPlatformGlobal.OperationState.Update;
            this.ruleSplitContainer.Panel2.Enabled = true;
            this.ruleSplitContainer.Panel1.Enabled = false;
            this.ruleTitleTextBox.Enabled = false;
        }

        private void ruleToolBtnListViewer_InnerListViewSelectedIndexChanged(object sender, EventArgs e)
        {
            var myItem = ruleToolBtnListViewer.SelectedItems[0];

            this.ruleTitleTextBox.Text = myItem.Text;
            this.ruleCateComboBox.SelectedValue = myItem.SubItems["cate"].Tag as string;
            this.ruleTradeComboBox.SelectedValue = myItem.SubItems["trade"].Tag as string;
            this.rulePnComboBox.SelectedValue = myItem.SubItems["pn"].Tag as string;
            this.ruleColorComboBox.SelectedValue = myItem.SubItems["color"].Tag as string;
            this.ruleDisableCheckBox.Checked = (int)(myItem.SubItems["state"].Tag) == 1 ? false : true;
        }

        /// <summary>
        /// generate barcode by selected barcode elements
        /// </summary>
        private string generateBarcodeTitle()
        {
            PipeAutoDataSet.BarcodeElementDicDataTable[] myTables = new PipeAutoDataSet.BarcodeElementDicDataTable[4];

            for (int i = 0; i < myTables.Length;i++ )
            {
                myTables[i] = new PipeAutoDataSet.BarcodeElementDicDataTable();
            }

            string myRet = string.Empty;

#if !DEBUG
            try
            {
#endif
                BarcodeElementDicTableAdapter myAdapter = new BarcodeElementDicTableAdapter();
                myAdapter.FillByCode(myTables[0], ruleCateComboBox.SelectedValue.ToString());
                myAdapter.FillByCode(myTables[1], ruleTradeComboBox.SelectedValue.ToString());
                myAdapter.FillByCode(myTables[2], rulePnComboBox.SelectedValue.ToString());
                myAdapter.FillByCode(myTables[3], ruleColorComboBox.SelectedValue.ToString());
                myRet = myTables[0][0].Code + "-" + myTables[1][0].Code + "-" + myTables[2][0].Code + "-" + myTables[3][0].Code;
#if !DEBUG
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return string.Empty;
            }
#endif

            return myRet;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            this.genderComboBox.SelectedIndex = 0;
            this.deptToolStrip.Visible = true;
            this.roleToolStrip.Visible = true;
            this.stockOutToolStrip.Visible = true;
            this.combSearchFlowLayoutPanel.AutoSize = true;


            //authority
            var myPrincipal = Thread.CurrentPrincipal;

            for (int i = mgrTabControl.TabPages.Count - 1; i >= 0; i--)
            {
                var myTab=mgrTabControl.TabPages[i];

                if (myPrincipal.IsInRole(myTab.Tag.ToString())==false)
                {
                    mgrTabControl.TabPages.RemoveAt(i);
                }
            }

            
        }

        private void ruleEleComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            //ensure that the first combobox's selected value is not null when exit app
            //and ensure that the last combobox's selected value is not null when enter app
            if (this.ruleCateComboBox.SelectedValue==null||
                this.ruleTradeComboBox.SelectedValue==null||
                this.rulePnComboBox.SelectedValue==null||
                this.ruleColorComboBox.SelectedValue==null)
            {
                return;
            }

            this.ruleTitleTextBox.Text = this.generateBarcodeTitle();
        }

        private void ruleToolBtnListViewer_DelBtnClick(object sender, EventArgs e)
        {
            if (MessageBox.Show(delConfirmMsg,"确认",MessageBoxButtons.YesNo)!=DialogResult.Yes)
            {
                return;
            }

            var myItem = this.ruleToolBtnListViewer.SelectedItems[0];

            try
            {
                StockTableAdapter myAdapter = new StockTableAdapter();
                myAdapter.DeleteByID(myItem.Tag as string);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            myItem.Remove();

            MessageBox.Show("成功！");

        }

        private void userTabPage_Enter(object sender, EventArgs e)
        {
            genderComboBox.SelectedIndex = 0;

#if !DEBUG
            try
            {
#endif
                var myAdapter=new RolesTableAdapter();

                roleBindingSource.DataSource = myAdapter.GetData();

                roleComboBox.DisplayMember = "title";
                roleComboBox.ValueMember = "id";

                userToolBtnListViewer.InnerListViewer.Items.Clear();

                var myUserAdapter = new UsersTableAdapter();

                var myTable = myUserAdapter.GetDataByLinked();

                foreach (var myRow in myTable)
                {
                    insertNewUser(myRow.ID, myRow.UName, myRow.Name, myRow.PWD, myRow.Gender, myRow.DeptID, myRow["depttitle"].ToString(), myRow.RoleID, myRow.State);

                }
#if !DEBUG

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
#endif


        }

        private void deptTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var myNode = deptTreeView.SelectedNode;

            if (myNode == null)
            {
                return;
            }

            deptTitleTextBox.Text = myNode.Text;
            deptDisableCheckBox.Checked = myNode.ForeColor == Color.Gray ? true : false;

            //root node
            if (myNode.Level==0)
            {
                this.setParentDeptLabel("无", Color.Black);
                return;
            }

            var myParentDeptTreeViewNode = MgrPlatformGlobal.LeveledRecurseTreeView(myNode.Parent.Tag.ToString(), parentDeptTreeView.Nodes[0],myNode.Parent.Level);

            if (myParentDeptTreeViewNode==null)
            {
                MessageBox.Show("数据错误！");
                return;
            }

            parentDeptTreeView.SelectedNode = myParentDeptTreeViewNode;

            this.setParentDeptLabel(myParentDeptTreeViewNode.Text,myParentDeptTreeViewNode.ForeColor);

            //expend right tree view
            this.expendNode(myParentDeptTreeViewNode);
        }

        /// <summary>
        /// set parent department label's text
        /// </summary>
        /// <param name="text"></param>
        /// <param name="state"></param>
        private void setParentDeptLabel(string text, Color state)
        {
            parentDeptLabel.Text = text;
            parentDeptLabel.ForeColor = state;

            if (state==Color.Gray)
            {
                parentDeptLabel.Text += "（停用）";
            }
        }

        private void deptDelToolStripButton_Click(object sender, EventArgs e)
        {
            if (deptTreeView.SelectedNode==null)
            {
                MessageBox.Show("请先选择一个部门！");
                return;
            }

            if (deptTreeView.SelectedNode.Level==0)
            {
                MessageBox.Show("公司不能被删除！");
                return;
            }

            string myDelMsg = delConfirmMsg;

            if (deptTreeView.SelectedNode.Nodes.Count>0)
            {
                myDelMsg = "该节点还有" + deptTreeView.SelectedNode.Nodes.Count + "个子部门，这些部门将被一起删除，"+delConfirmMsg;
            }

            if (MessageBox.Show(myDelMsg,confirmCaption,MessageBoxButtons.YesNo)!=DialogResult.Yes)
            {
                return;
            }

            try
            {
                DepartmentsTableAdapter myAdapter = new DepartmentsTableAdapter();
                myAdapter.DeleteByID(deptTreeView.SelectedNode.Tag.ToString());


            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            parentDeptTreeView.SelectedNode.Remove();
            deptTreeView.SelectedNode.Remove();
            MessageBox.Show("成功！");
        }

        private void deptInsertToolStripButton_Click(object sender, EventArgs e)
        {
            var myNode=deptTreeView.SelectedNode;

            if (myNode==null)
            {
                MessageBox.Show("请先选择一个部门！");
                return;
            }

            //need to add level 1 node
            if (myNode.Level == 0)
            {
                var myParentNode = parentDeptTreeView.Nodes[0];
                parentDeptTreeView.SelectedNode = myParentNode;
                //this.setParentDeptLabel(myParentNode.Text, myParentNode.ForeColor);
                this.parentDeptTreeView.Enabled = false;
                this.parentDeptTreeView.CollapseAll();
            }
            else
            {




                if (myNode.ForeColor == Color.Gray)
                {
                    MessageBox.Show("请先启用该部门！");
                    return;
                }

                this.parentDeptTreeView.Enabled = true;
                this.deptTreeView_AfterSelect(deptInsertToolStripButton, null);
            }

            deptTitleTextBox.Text = string.Empty;


            deptDisableCheckBox.Checked = false;
            deptSplitContainer.Panel2.Enabled = true;
            deptSplitContainer.Panel1.Enabled = false;

            this.opState = MgrPlatformGlobal.OperationState.Add;
        }

        private void deptTabPage_Enter(object sender, EventArgs e)
        {
            this.deptTreeView.Nodes.Clear();
            this.parentDeptTreeView.Nodes.Clear();

            int myLevel = 0;
            //TreeNodeCollection myParentNodes = null;

            while (true)
            {
#if !DEBUG
                try
                {
#endif
                    DepartmentsTableAdapter myAdapter = new DepartmentsTableAdapter();

                    var myTable = myAdapter.GetDataByLevel(myLevel);

                    if (myTable.Count==0)
                    {
                        break;
                    }

                    myLevel++;

                    foreach (var myRow in myTable)
                    {
                        //root node
                        if (myRow.Level==0)
                        {
                            deptTreeView.Nodes.Add(new TreeNode { Text = myRow.Title, Tag = myRow.ID, ForeColor = myRow.State == 1 ? Color.Black : Color.Gray });
                            parentDeptTreeView.Nodes.Add(new TreeNode { Text = myRow.Title, Tag = myRow.ID, ForeColor = myRow.State == 1 ? Color.Black : Color.Gray });
                            continue;
                        }

                        //child node

                        //get parent node
                        var myNode = MgrPlatformGlobal.LeveledRecurseTreeView( myRow.ParentDeptID,deptTreeView.Nodes[0],myRow.Level-1);

                        if (myNode==null)
                        {
                            MessageBox.Show("数据错误！");
                            return;
                        }

                        myNode.Nodes.Add(new TreeNode { Text = myRow.Title, Tag = myRow.ID, ForeColor = myRow.State == 1 ? Color.Black : Color.Gray });

                        myNode = MgrPlatformGlobal.LeveledRecurseTreeView(myRow.ParentDeptID, parentDeptTreeView.Nodes[0],myRow.Level-1);

                        myNode.Nodes.Add(new TreeNode { Text = myRow.Title, Tag = myRow.ID, ForeColor = myRow.State == 1 ? Color.Black : Color.Gray });


                    }
#if !DEBUG
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
#endif
            }

            

            try
            {
                deptTreeView.Nodes[0].Expand();
                //deptTreeView.SelectedNode = deptTreeView.Nodes[0];
                parentDeptTreeView.Nodes[0].Expand();
            }
            catch (ArgumentOutOfRangeException)
            {
            	
            }

        }



        private void deptCancelButton_Click(object sender, EventArgs e)
        {
            this.opState = MgrPlatformGlobal.OperationState.Null;
            deptSplitContainer.Panel1.Enabled = true;
            deptSplitContainer.Panel2.Enabled = false;
        }

        private void deptSaveButton_Click(object sender, EventArgs e)
        {
            
            if (deptTitleTextBox.Text.Trim()==string.Empty)
            {
                MessageBox.Show("名称不能为空！");
                return;
            }

            //right node
            var myRightNode=parentDeptTreeView.SelectedNode;

            //left operating node
            var myLeftNode = deptTreeView.SelectedNode;

            if (myRightNode==null)
            {
                MessageBox.Show("请先选择一个父部门！");
                return;
            }

            if (myRightNode.ForeColor==Color.Gray)
            {
                MessageBox.Show("请先启用父部门！");
                return;
            }

            


            switch(this.opState)
            {
                case MgrPlatformGlobal.OperationState.Add:
                    {
                        string myID=Guid.NewGuid().ToString();
                        try
                        {
                            DepartmentsTableAdapter myAdapter = new DepartmentsTableAdapter();
                            myAdapter.InsertQuery(myID, deptTitleTextBox.Text, myRightNode.Level + 1, myRightNode.Tag.ToString(), deptDisableCheckBox.Checked == false ? 1 : 2);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }
                        //parent node has changed
                        if (myRightNode.Tag.ToString() != myLeftNode.Parent.Tag.ToString())
                        {
                            myLeftNode = MgrPlatformGlobal.LeveledRecurseTreeView(myRightNode.Tag.ToString(), deptTreeView.Nodes[0], myRightNode.Level);
                        }


                        //left node equals right node as parent node
                        myLeftNode.Nodes.Add(new TreeNode { Text = deptTitleTextBox.Text, Tag = myID, ForeColor = deptDisableCheckBox.Checked == false ? Color.Black : Color.Gray });
                        myRightNode.Nodes.Add(new TreeNode { Text = deptTitleTextBox.Text, Tag = myID, ForeColor = deptDisableCheckBox.Checked == false ? Color.Black : Color.Gray });

                        break;
                    }
                case MgrPlatformGlobal.OperationState.Update:
                    {
                        //validation
                        if (myLeftNode.Tag.ToString() == myRightNode.Tag.ToString())
                        {
                            MessageBox.Show("不能把自己作为自己的父部门！");
                            return;
                        }

                        //level lower
                        if (myLeftNode.Level<myRightNode.Level)
                        {
                            var myIteratNode = myRightNode.Parent;
                            while (true)
                            {
                                //in the root
                                if (myIteratNode==null)
                                {
                                    break;
                                }

                                if (myLeftNode.Tag.ToString()==myIteratNode.Tag.ToString())
                                {
                                    MessageBox.Show("父部门不可以是自己的子部门！");
                                    return;
                                }

                                myIteratNode = myIteratNode.Parent;
                            }
                            
                        }

                        string parentID = null;
                        int myLevel=0;
                        int myEnabled=deptDisableCheckBox.Checked==false?1:2;

                        //not root department
                        if (myLeftNode.Level!=0)
                        {
                            //parent department need to be enabled first
                            if (myLeftNode.Parent.ForeColor==Color.Gray&&deptDisableCheckBox.Checked==false)
                            {
                                MessageBox.Show("请先启用父部门！");
                                return;
                            }

                            myLevel=parentDeptTreeView.SelectedNode.Level+1;
                            parentID = parentDeptTreeView.SelectedNode.Tag.ToString();
                        }

                        //have sub department
                        if (myLeftNode.Nodes.Count != 0)
                        {
                            string myConfirmMsg = "该部门还有" + myLeftNode.Nodes.Count.ToString() + "个子部门，" + delConfirmMsg;


                            if (MessageBox.Show(myConfirmMsg, confirmCaption, MessageBoxButtons.YesNo) != DialogResult.Yes)
                            {
                                return;
                            }
                        }

                        try
                        {
                            DepartmentsTableAdapter myAdapter = new DepartmentsTableAdapter();
                            myAdapter.UpdateQuery(deptTitleTextBox.Text, myLevel, parentID, myEnabled, myLeftNode.Tag.ToString());
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }

                        this.deptTabPage_Enter(deptSaveButton, null);

                        break;
                    }

            }

            this.expendNode(myLeftNode.Parent);
            this.expendNode(myRightNode);

            this.opState = MgrPlatformGlobal.OperationState.Null;
            deptSplitContainer.Panel2.Enabled = false;
            deptSplitContainer.Panel1.Enabled = true;
            MessageBox.Show("成功！");
        }

        /// <summary>
        /// expend tree node
        /// </summary>
        /// <param name="parentNode"></param>
        private void expendNode(TreeNode parentNode)
        {
            var myNode= parentNode;
            while(myNode!=null)
            {
                myNode.Expand();
                myNode = myNode.Parent;
            }
        }

        private void parentDeptTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var myNode=parentDeptTreeView.SelectedNode;
            if (myNode==null)
            {
                return;
            }


            this.setParentDeptLabel(myNode.Text, myNode.ForeColor);

        }

        private void deptUpdateToolStripButton_Click(object sender, EventArgs e)
        {
            if (deptTreeView.SelectedNode==null)
            {
                MessageBox.Show("请选择一个部门！");
                return;
            }

            var myLeftNode = deptTreeView.SelectedNode;

            //root node 
            if (myLeftNode.Level==0)
            {
                parentDeptTreeView.Enabled = false;
                deptDisableCheckBox.Enabled = false;
            }
            else
            {
                parentDeptTreeView.Enabled = true;
                deptDisableCheckBox.Enabled = true;
            }

            //parentDeptTreeView.Enabled = false;

            deptSplitContainer.Panel1.Enabled = false;
            deptSplitContainer.Panel2.Enabled = true;

            opState = MgrPlatformGlobal.OperationState.Update;
        }

        private void membershipTabPage_Enter(object sender, EventArgs e)
        {
            
            

            roleTreeView.Nodes.Clear();

            try
            {
                RolesTableAdapter myAdapter = new RolesTableAdapter();
                var myTable = myAdapter.GetData();


                //fill roles
                foreach (var myRow in myTable)
                {
                    var myNode = new TreeNode { Text = myRow.Title, Tag = myRow.ID };
                    roleTreeView.Nodes.Add(myNode);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            appComboBox.SelectedIndex = 0;
            appListBox.DisplayMember = "title";
            appListBox.ValueMember = "id";
        }

        private void appComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            //appDicBindingSource.Clear();

#if !DEBUG
            try
            {
#endif

            this.FillAppListBox();

                AppDicTableAdapter myAdapter = new AppDicTableAdapter();

                for (int i = 0; i < roleTreeView.Nodes.Count;i++ )
                {
                    var myNode = roleTreeView.Nodes[i];

                    myNode.Nodes.Clear();

                    var myAppTable = myAdapter.GetDataByRole(myNode.Tag.ToString(), appComboBox.SelectedIndex + 1);

                    foreach (var myAppRow in myAppTable)
                    {
                        myNode.Nodes.Add(new TreeNode { Text = myAppRow.Title, Tag = myAppRow.ID });
                    }
                }
#if !DEBUG
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
#endif

            
        }

        /// <summary>
        /// fill app list box
        /// </summary>
        private void FillAppListBox()
        {
            var myAdapter = new AppDicTableAdapter();

            var myRoleNode = roleTreeView.SelectedNode;

            if (myRoleNode == null)
            {
                appDicBindingSource.DataSource = myAdapter.GetDataByType(appComboBox.SelectedIndex + 1);
            }
            else
            {

                if (myRoleNode.Level == 1)
                {
                    appDicBindingSource.DataSource = myAdapter.GetDataFreeByRole(appComboBox.SelectedIndex + 1, myRoleNode.Parent.Tag.ToString());
                }
                else
                {
                    appDicBindingSource.DataSource = myAdapter.GetDataFreeByRole(appComboBox.SelectedIndex + 1, myRoleNode.Tag.ToString());
                }
            }
        }

        private void roleInsertToolStripButton_Click(object sender, EventArgs e)
        {
            enableRoleEdit();
            roleTitleToolStripTextBox.Text = string.Empty;
            this.opState = MgrPlatformGlobal.OperationState.Add;
        }

        /// <summary>
        /// enable role edit control and disable role tree view
        /// </summary>
        private void enableRoleEdit()
        {
            roleInsertToolStripButton.Enabled = false;
            roleDelToolStripButton.Enabled = false;
            roleUpdateToolStripButton.Enabled = false;
            roleTitleToolStripTextBox.Enabled = true;
            roleSaveToolStripButton.Enabled = true;
            roleCancelToolStripButton.Enabled = true;
            roleTreeView.Enabled = false;
        }

        private void roleSaveToolStripButton_Click(object sender, EventArgs e)
        {
            if (roleTitleToolStripTextBox.Text.Trim()==string.Empty)
            {
                MessageBox.Show("名称不能为空！");
                return;
            }

            switch (opState)
            {
                case MgrPlatformGlobal.OperationState.Add:
                    {
                        string myID=Guid.NewGuid().ToString();

                        try
                        {
                            RolesTableAdapter myAdapter = new RolesTableAdapter();

                            //redundant title
                            if (myAdapter.ScalarByTitle(roleTitleToolStripTextBox.Text)>0)
                            {
                                MessageBox.Show("名称重复！");
                                return;
                            }

                            

                            //insert 
                            myAdapter.InsertQuery(myID, roleTitleToolStripTextBox.Text, 1);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }

                        roleTreeView.Nodes.Add(new TreeNode { Text = roleTitleToolStripTextBox.Text, Tag = myID });
                        
                        break;
                    }
                case MgrPlatformGlobal.OperationState.Update:
                    {
                        var myNode=roleTreeView.SelectedNode;
                        if (myNode.Level==1)
                        {
                            myNode=myNode.Parent;
                        }

                        try
                        {
                            RolesTableAdapter myAdapter = new RolesTableAdapter();

                            if (myNode.Text != roleTitleToolStripTextBox.Text)
                            {
                                if (myAdapter.ScalarByTitle(roleTitleToolStripTextBox.Text)>0)
                                {
                                    MessageBox.Show("名称重复！");
                                    return;
                                }
                            }

                            myAdapter.UpdateQuery(roleTitleToolStripTextBox.Text, 1, myNode.Tag.ToString());

                            myNode.Text = roleTitleToolStripTextBox.Text;
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }

                        break;
                    }
            }

            MessageBox.Show("成功！");
            this.opState = MgrPlatformGlobal.OperationState.Null;
            disableRoleEdit();
        }

        /// <summary>
        /// disable row edit controls
        /// </summary>
        private void disableRoleEdit()
        {
            roleInsertToolStripButton.Enabled = true;
            roleDelToolStripButton.Enabled = true;
            roleUpdateToolStripButton.Enabled = true;
            roleTitleToolStripTextBox.Enabled = false;
            roleSaveToolStripButton.Enabled = false;
            roleCancelToolStripButton.Enabled = false; 
            roleTreeView.Enabled = true;
        }

        private void roleDelToolStripButton_Click(object sender, EventArgs e)
        {
            var myNode = roleTreeView.SelectedNode;

            if (myNode==null)
            {
                MessageBox.Show("请先选择一个角色！");
                return;
            }

            if (MessageBox.Show(delConfirmMsg,confirmCaption,MessageBoxButtons.YesNo)!= DialogResult.Yes)
            {
                return;
            }

            if (myNode.Level==1)
            {
                myNode = myNode.Parent;
            }

            try
            {
                RolesTableAdapter myAdapter = new RolesTableAdapter();

                myAdapter.DeleteQuery(myNode.Tag.ToString());
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            myNode.Remove();

            MessageBox.Show("成功！");
        }

        private void roleTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var myNode = roleTreeView.SelectedNode;

            if (myNode==null)
            {
                return;
            }

            if (myNode.Level == 1)
            {
                roleTitleToolStripTextBox.Text = myNode.Parent.Text;
            }
            else
            {

                roleTitleToolStripTextBox.Text = myNode.Text;
            }

            this.FillAppListBox();
        }

        private void roleUpdateToolStripButton_Click(object sender, EventArgs e)
        {
            this.opState = MgrPlatformGlobal.OperationState.Update;
            enableRoleEdit();
        }

        private void grantButton_Click(object sender, EventArgs e)
        {
            if (appListBox.SelectedItem == null)
            {
                MessageBox.Show("请选择权限！");
                return;
            }

            var myNode = roleTreeView.SelectedNode;

            if (myNode == null)
            {
                MessageBox.Show("请选择角色！");
                return;
            }

            if (myNode.Level == 1)
            {
                myNode = myNode.Parent;
            }

            try
            {
                MemberShipTableAdapter myAdapter = new MemberShipTableAdapter();
                myAdapter.InsertQuery(myNode.Tag.ToString(), appListBox.SelectedValue.ToString());
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }


            myNode.Nodes.Add(new TreeNode { Text = appListBox.Text, Tag = appListBox.SelectedValue.ToString() });
            myNode.Expand();

            this.FillAppListBox();
            //this.appComboBox_SelectedIndexChanged(sender, null);
            //MessageBox.Show("成功!");
        }

        private void appListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            roleTreeView.Focus();
        }

        private void depriveButton_Click(object sender, EventArgs e)
        {
            var myNode=roleTreeView.SelectedNode;

            if (myNode==null)
            {
                MessageBox.Show("请选择一个角色！");
            }

            try
            {
                MemberShipTableAdapter myAdapter = new MemberShipTableAdapter();

                if (myNode.Level==0)
                {
                    myAdapter.DeleteByRole(myNode.Tag.ToString());
                }
                else
                {
                    myAdapter.DeleteQuery(myNode.Parent.Tag.ToString(), myNode.Tag.ToString());
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            if (myNode.Level==0)
            {
                myNode.Nodes.Clear();
            }
            else
            {
                myNode.Remove();
            }

            this.FillAppListBox();
        }

        private void userToolBtnListViewer_NewBtnClick(object sender, EventArgs e)
        {
            uNameTextBox.Text = string.Empty;
            nameTextBox.Text = string.Empty;
            pwdTextBox.Text = string.Empty;
            deptLinkLabel.Text = "点击选择部门";
            uDisableCheckBox.Checked = false;

            userSplitContainer.Panel1.Enabled = false;
            userSplitContainer.Panel2.Enabled = true;
            uNameTextBox.ReadOnly = false;

            opState = MgrPlatformGlobal.OperationState.Add;
        }

        private void deptLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DeptSelectForm myForm = new DeptSelectForm();
            myForm.ShowDialog(this);

        }

        private void uCancelButton_Click(object sender, EventArgs e)
        {
            userSplitContainer.Panel2.Enabled = false;
            userSplitContainer.Panel1.Enabled = true;

            opState = MgrPlatformGlobal.OperationState.Null;
        }

        private void uOKButton_Click(object sender, EventArgs e)
        {
            if (uNameTextBox.Text.Trim()==string.Empty)
            {
                MessageBox.Show("用户名不能为空！");
                return;
            }

            if (pwdTextBox.Text.Trim()==string.Empty)
            {
                MessageBox.Show("密码不能为空！");
                return;
            }

            string myHashedPwd = MgrPlatformGlobal.ComputerMD5(pwdTextBox.Text);

            if (nameTextBox.Text.Trim()==string.Empty)
            {
                MessageBox.Show("姓名不能为空！");
                return;
            }

            if (deptLinkLabel.Tag==null)
            {
                MessageBox.Show("请选择部门！");
                return;
            }

            switch(opState)
            {
                case MgrPlatformGlobal.OperationState.Add:
                    {
                        string myId=Guid.NewGuid().ToString();

                        try
                        {
                            UsersTableAdapter myAdapter = new UsersTableAdapter();

                            if (myAdapter.ScalarByUName(uNameTextBox.Text)>0)
                            {
                                MessageBox.Show("用户名重复！");
                                return;
                            }

                            myAdapter.InsertQuery(myId, uNameTextBox.Text, myHashedPwd, nameTextBox.Text, genderComboBox.SelectedIndex + 1, deptLinkLabel.Tag.ToString(), roleComboBox.SelectedValue.ToString(), 1, uDisableCheckBox.Checked == true ? 2 : 1);

                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }

                        insertNewUser(myId, uNameTextBox.Text, nameTextBox.Text, myHashedPwd, genderComboBox.SelectedIndex + 1, deptLinkLabel.Tag.ToString(), deptLinkLabel.Text, roleComboBox.SelectedValue.ToString(), uDisableCheckBox.Checked == true ? 2 : 1);

                        break;
                    }
                case MgrPlatformGlobal.OperationState.Update:
                    {
                        var myItem = userToolBtnListViewer.SelectedItems[0];

                        try
                        {
                            UsersTableAdapter myAdapter = new UsersTableAdapter();
                            
                            if (uNameTextBox.Text!=userToolBtnListViewer.SelectedItems[0].Text&&myAdapter.ScalarByUName(uNameTextBox.Text)>0)
                            {
                                MessageBox.Show("用户名重复！");
                                return;
                            }

                            myAdapter.UpdateQuery(uNameTextBox.Text, myHashedPwd, nameTextBox.Text, genderComboBox.SelectedIndex + 1, deptLinkLabel.Tag.ToString(), roleComboBox.SelectedValue.ToString(), 1, uDisableCheckBox.Checked == false ? 1 : 2, userToolBtnListViewer.SelectedItems[0].Tag.ToString());
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }

                        myItem.Text = uNameTextBox.Text;
                        myItem.SubItems["pwd"].Tag = myHashedPwd;
                        myItem.SubItems["name"].Tag = myItem.SubItems["name"].Text = nameTextBox.Text;
                        myItem.SubItems["gender"].Text = genderComboBox.SelectedIndex == 0 ? "男" : "女";
                        myItem.SubItems["gender"].Tag = genderComboBox.SelectedIndex + 1;
                        myItem.SubItems["dept"].Tag = deptLinkLabel.Tag;
                        myItem.SubItems["dept"].Text = deptLinkLabel.Text;
                        myItem.SubItems["role"].Tag = roleComboBox.SelectedValue;
                        myItem.SubItems["state"].Tag = uDisableCheckBox.Checked == false ? 1 : 2;



                        break;
                    }
            }

            pwdTextBox.Text = myHashedPwd;

            opState = MgrPlatformGlobal.OperationState.Null;
            userSplitContainer.Panel1.Enabled = true;
            userSplitContainer.Panel2.Enabled = false;
            MessageBox.Show("成功！");
        }

        private void insertNewUser(string id, string uname, string name, string pwd, int gender, string deptID, string deptTitle, string roleID, int state, int type=1)
        {
            ListViewItem myItem = new ListViewItem { Text = uname, Tag = id };
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "name", Text = name, Tag = name });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "gender", Text = gender == 1 ? "男" : "女", Tag = gender });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "state", Text = state == 2 ? "停用" : "启用", Tag = state });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "pwd", Tag = pwd });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "dept", Text = deptTitle, Tag = deptID });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "role", Tag = roleID });
            myItem.SubItems.Add(new ListViewItem.ListViewSubItem { Name = "state", Tag = state });
            userToolBtnListViewer.InnerListViewer.Items.Add(myItem);
        }

        private void userToolBtnListViewer_InnerListViewSelectedIndexChanged(object sender, EventArgs e)
        {
            if (userToolBtnListViewer.SelectedItems.Count==0)
            {
                return;
            }

            var myItem = userToolBtnListViewer.SelectedItems[0];

            uNameTextBox.Text = myItem.Text;
            nameTextBox.Text = myItem.SubItems["name"].Text;
            pwdTextBox.Text = myItem.SubItems["pwd"].Tag.ToString();
            genderComboBox.SelectedIndex = int.Parse(myItem.SubItems["gender"].Tag.ToString()) - 1;
            deptLinkLabel.Text = myItem.SubItems["dept"].Text;
            deptLinkLabel.Tag = myItem.SubItems["dept"].Tag.ToString();
            roleComboBox.SelectedValue = myItem.SubItems["role"].Tag.ToString();
            uDisableCheckBox.Checked = int.Parse(myItem.SubItems["state"].Tag.ToString()) == 1 ? false : true;
        }

        private void userToolBtnListViewer_UpdateBtnClick(object sender, EventArgs e)
        {
            userSplitContainer.Panel2.Enabled = true;
            userSplitContainer.Panel1.Enabled = false;
            uNameTextBox.ReadOnly = true;
            opState = MgrPlatformGlobal.OperationState.Update;
        }

        private void userToolBtnListViewer_DelBtnClick(object sender, EventArgs e)
        {
            var mySelected=userToolBtnListViewer.SelectedItems[0];
            if (mySelected.Text.ToLower()=="admin")
            {
                MessageBox.Show("管理员账户不能删除！");
                return;
            }

            string myMsg = delConfirmMsg;

            if (MessageBox.Show(myMsg,confirmCaption,MessageBoxButtons.YesNo)!=DialogResult.Yes)
            {
                return;
            }

            var myNode = userToolBtnListViewer.SelectedItems[0];

            try
            {
                UsersTableAdapter myAdapter = new UsersTableAdapter();
                myAdapter.DeleteQuery(myNode.Tag.ToString());
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            myNode.Remove();
            MessageBox.Show("成功！");
        }

        private void stockOutTabPage_Enter(object sender, EventArgs e)
        {
            soStateTitledComboBox.ContextComboBox.SelectedIndex = 0;
            soOpMethodTitledComboBox.ContextComboBox.SelectedIndex = 0;
            try
            {
                BarcodeElementDicTableAdapter myAdapter = new BarcodeElementDicTableAdapter();


                bindingComboboxDataSource(soCateTitledComboBox.ContextComboBox, new BindingSource(), myAdapter.GetDataByTypeState(1,1));
                bindingComboboxDataSource(soTradeTitledComboBox.ContextComboBox, new BindingSource(), myAdapter.GetDataByTypeState(2, 1));
                //bindingComboboxDataSource(soPnTitledComboBox.ContextComboBox, new BindingSource(), myAdapter.GetDataByTypeState(3, 1));
                //bindingComboboxDataSource(soColorTitledComboBox.ContextComboBox, new BindingSource(), myAdapter.GetDataByTypeState(4, 1));

                //process intelligent suggestion
                soPnIntelligentSuggestion.Subscribe(soPnTitledTextBox.ContextTextBox);
                soPnIntelligentSuggestion.DataSource = myAdapter.GetDataByTypeState(3, 1);

                soPnIntelligentSuggestion.DisplayedColumns.Add("title");
                soPnIntelligentSuggestion.DisplayedColumns.Add("code");
                soPnIntelligentSuggestion.DisplayedColumns.Add("comment");

                soPnIntelligentSuggestion.ColumnAlias.Add("title", "名称");
                soPnIntelligentSuggestion.ColumnAlias.Add("code", "编码");
                soPnIntelligentSuggestion.ColumnAlias.Add("comment", "备注");

                soPnIntelligentSuggestion.FilterColumn = "pinyincode";

                soPnIntelligentSuggestion.SuggestionAcceptedEvent += new Arthasliu.Controls.IntelligentSuggestion.SuggestionAcceptedEventHandler(soPnIntelligentSuggestion_SuggestionAcceptedEvent);

                soColorIntelligentSuggestion.Subscribe(soColorTitledTextBox.ContextTextBox);
                soColorIntelligentSuggestion.DataSource = myAdapter.GetDataByTypeState(4, 1);

                soColorIntelligentSuggestion.DisplayedColumns.Add("title");
                soColorIntelligentSuggestion.DisplayedColumns.Add("code");
                soColorIntelligentSuggestion.DisplayedColumns.Add("comment");

                soColorIntelligentSuggestion.ColumnAlias.Add("title", "名称");
                soColorIntelligentSuggestion.ColumnAlias.Add("code", "编码");
                soColorIntelligentSuggestion.ColumnAlias.Add("comment", "备注");

                soColorIntelligentSuggestion.FilterColumn = "pinyincode";

                soColorIntelligentSuggestion.SuggestionAcceptedEvent += new Arthasliu.Controls.IntelligentSuggestion.SuggestionAcceptedEventHandler(soColorIntelligentSuggestion_SuggestionAcceptedEvent);

                soBeginDateTimePicker.Value = DateTime.Now.AddMonths(0-Properties.Settings.Default.StockOutDateSpan).Date;
                soEndDateTimePicker.Value = DateTime.Now.Date;

                //fillNewStockOutDataGridView();
                stockOutResultTabControl_SelectedIndexChanged(stockOutTabPage, null);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            //stockOutResultTabControl.SelectedIndex = 0;
            NewStockOutModel();
        }

        void soColorIntelligentSuggestion_SuggestionAcceptedEvent(object sender, TemplatedEventArgs<DataGridViewSelectedRowCollection> e)
        {
            soColorTitledTextBox.Context = e.Data[0].Cells["title"].Value.ToString();
            soColorTitledTextBox.Tag = e.Data[0].Cells["code"].Value.ToString();
        }

        void soPnIntelligentSuggestion_SuggestionAcceptedEvent(object sender, TemplatedEventArgs<DataGridViewSelectedRowCollection> e)
        {
            soPnTitledTextBox.Context = e.Data[0].Cells["title"].Value.ToString();
            soPnTitledTextBox.Tag = e.Data[0].Cells["code"].Value.ToString();
        }

        /// <summary>
        /// fill new stock out docs data grid view
        /// </summary>
        private void fillNewStockOutDataGridView()
        {
            var myTable = newStockOutDataGridView.DataSource as PipeAutoDataSet.VisualStockOutDocsDataTable;
            if (myTable!=null)
            {
                myTable.Clear();
            }


            try
            {
                VisualStockOutDocsTableAdapter myAdapter = new VisualStockOutDocsTableAdapter();
                newStockOutDataGridView.DataSource = myAdapter.GetDataByState(1);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }


        }

        private void newStockOutToolStripButton_Click(object sender, EventArgs e)
        {
            StockOutForm myForm = new StockOutForm();
            myForm.OpState = MgrPlatformGlobal.OperationState.Add;
            myForm.ShowDialog(this);

            fillNewStockOutDataGridView();
        }

        private void newSOTabPage_Enter(object sender, EventArgs e)
        {
            try
            {
                
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void stockOutResultTabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (stockOutResultTabControl.SelectedIndex==0)
            {
                NewStockOutModel();

                //fill new stock outs data grid view
                fillNewStockOutDataGridView();


            }
            else
            {
                QueryStockOutModel();
            }
        }

        private void voidSOToolStripButton_Click(object sender, EventArgs e)
        {
            int myInt = 0;

            try
            {
                myInt=validateChecked(newStockOutDataGridView,newSoCheckColumn.Name);
            }
            catch (MsgBoxException ex)
            {
                MessageBox.Show(ex.Message,ex.Caption);
                return;
            }

            

            var myIdentity = Thread.CurrentPrincipal.Identity as WinformIdentity;

            if (MessageBox.Show("即将作废，是否继续？", confirmCaption, MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            for (int i = 0; i < newStockOutDataGridView.Rows.Count;i++ )
            {
                if (myInt==0)
                {
                    break; 
                }

                var myCell=newStockOutDataGridView.Rows[i].Cells[newSoCheckColumn.Name] as DataGridViewCheckBoxCell;

                //checked row
                if (myCell.Value!=null&&bool.Parse(myCell.Value.ToString())==true)
                {
                    myInt--;

                    var myRow = newStockOutDataGridView.Rows[i];

                    var myID = myRow.Cells[newSoCheckColumn.Name].Value.ToString();

                    //var myIndex = myRow.Index;

                    try
                    {
                        var mySoDocAdapter = new StockOutDocsTableAdapter();
                        mySoDocAdapter.VoidStockOutDoc(myIdentity.ID, myID);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }

                    var myTable = newStockOutDataGridView.DataSource as PipeAutoDataSet.VisualStockOutDocsDataTable;

                    //remove in data source
                    foreach (var myDSRow in myTable)
                    {
                        if (myDSRow.ID == myID)
                        {
                            myTable.Rows.Remove(myDSRow);
                            i--;
                            break;
                        }
                    }
                }
            }

            

            MessageBox.Show("成功！");

        }

        private int validateChecked(DataGridView gridView,string checkColumnName)
        {
            gridView.CommitEdit(DataGridViewDataErrorContexts.Display);
            int myRet = 0;

            for (int i = 0; i < gridView.Rows.Count;i++ )
            {

                var myCell = gridView.Rows[i].Cells[checkColumnName] as DataGridViewCheckBoxCell;

                if (myCell.Value!=null&&bool.Parse(myCell.Value.ToString())!=false)
                {
                    myRet++;
                }
            }

            //gridView.BeginEdit();

            if (myRet==0)
            {
                throw new MsgBoxException("请钩择一条记录！","错误");
            }
            return myRet;
        }

        private void querySOToolStripButton_Click(object sender, EventArgs e)
        {
            //process command
            SqlCommand myFilterCmd = new SqlCommand { CommandText = string.Empty, CommandType = CommandType.Text };


            //stock out document filter
            StringBuilder myBuilder= new StringBuilder(" where createtime between @beginTime and @endtime");
            myFilterCmd.Parameters.Add(new SqlParameter { ParameterName = "@begintime", Value = soBeginDateTimePicker.Value.Date,DbType=DbType.DateTime });
            myFilterCmd.Parameters.Add(new SqlParameter { ParameterName = "@endtime", Value = soEndDateTimePicker.Value.Date.AddDays(1),DbType=DbType.DateTime });

            
            if (soStateTitledComboBox.Checked == true)
            {
                myBuilder.Append(" and state=@state");
                myFilterCmd.Parameters.Add(new SqlParameter { ParameterName = "@state", Value = soStateTitledComboBox.ContextComboBox.SelectedIndex + 1, DbType = DbType.Int32 });
            }

            if (soOpMethodTitledComboBox.Checked == true)
            {
                myBuilder.Append(" and stockoutmethod=@stockoutmethod");
                myFilterCmd.Parameters.Add(new SqlParameter { ParameterName = "@stockoutmethod", Value = soOpMethodTitledComboBox.ContextComboBox.SelectedIndex + 1, DbType = DbType.Int32 });
            }

            //stock out records filter

            int myRecFilter = 0;

            //count stock out records filters
            try
            {
                if (soCateTitledComboBox.Checked == true)
                {
                    myRecFilter++;
                }

                if (soTradeTitledComboBox.Checked == true)
                {
                    myRecFilter++;
                }

                if (soPnTitledTextBox.Checked == true)
                {
                    if (soPnTitledTextBox.Context==string.Empty||
                        soPnTitledTextBox.Tag==null||
                        soPnTitledTextBox.Tag.ToString()==string.Empty)
                    {
                        throw new MsgBoxException("“型号”不合法，请检查！", "错误");
                    }

                    myRecFilter++;
                }

                if (soColorTitledTextBox.Checked==true)
                {
                    if (soColorTitledTextBox.Context==string.Empty||
                        soColorTitledTextBox.Tag==null||
                        soColorTitledTextBox.Tag.ToString()==string.Empty)
                    {
                        throw new MsgBoxException("“颜色”不合法，请检查", "错误");
                    }

                    myRecFilter++;
                }
            }
            catch (MsgBoxException ex)
            {
                MessageBox.Show(ex.Message, ex.Caption);
                return;
            }

            

            //need add stock out record filters
            if (myRecFilter > 0)
            {
                myBuilder.Append(" and id in (select distinct docid from stockoutrecs where 1=1");

                if (soCateTitledComboBox.Checked == true)
                {
                    myBuilder.Append(" and catecode=@catecode");
                    myFilterCmd.Parameters.Add(new SqlParameter { ParameterName = "@catecode", Value = soCateTitledComboBox.ContextComboBox.SelectedValue.ToString(), DbType = DbType.String });
                }

                if (soTradeTitledComboBox.Checked == true)
                {
                    myBuilder.Append(" and tradecode=@tradecode");
                    myFilterCmd.Parameters.Add(new SqlParameter { ParameterName = "@tradecode", Value = soTradeTitledComboBox.ContextComboBox.SelectedValue.ToString() });
                }

                if (soPnTitledTextBox.Checked == true)
                {
                    myBuilder.Append(" and pncode=@pncode");
                    myFilterCmd.Parameters.Add(new SqlParameter { ParameterName = "@pncode", Value = soPnTitledTextBox.Tag.ToString(), DbType = DbType.String });
                }

                if (soColorTitledTextBox.Checked == true)
                {
                    myBuilder.Append(" and colorcode=@colorcode");
                    myFilterCmd.Parameters.Add(new SqlParameter { ParameterName = "@colorcode", Value = soColorTitledTextBox.Tag.ToString(), DbType = DbType.String });
                }

                myBuilder.Append(")");
            }



            myFilterCmd.CommandText = myBuilder.ToString();

#if !DEBUG
            try
            {

            
#endif

            var  myAdapter = new VisualStockOutDocsTableAdapter();
            var myTable = myAdapter.GetDataByCmdFilter(myFilterCmd);

            if (soSearchDataGridView.DataSource != null)
            {
                var mySearchTable = soSearchDataGridView.DataSource as PipeAutoDataSet.VisualStockOutDocsDataTable;
                mySearchTable.Clear();
            }


            soSearchDataGridView.DataSource = myTable;

#if !DEBUG
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
#endif

            


        }


        private void financialToolStripButton_Click(object sender, EventArgs e)
        {
            int mySelected = 0;

            try
            {
                mySelected = validateChecked(newStockOutDataGridView,newSoCheckColumn.Name);
            }
            catch (MsgBoxException ex)
            {
                MessageBox.Show(ex.Message,ex.Caption);
                return;
            }

            var myUID = (Thread.CurrentPrincipal.Identity as WinformIdentity).ID;

            for (int i = 0; i < newStockOutDataGridView.Rows.Count;i++ )
            {
                if (mySelected==0)
                {
                    break;
                }

                var myRow=newStockOutDataGridView.Rows[i];

                //checked row
                if (myRow.Cells[newSoCheckColumn.Name].Value!=null&&bool.Parse(myRow.Cells[newSoCheckColumn.Name].Value.ToString())==true)
                {
                    mySelected--;
                    try
                    {
                        var myAdapter = new VisualStockOutDocsTableAdapter();

                        myAdapter.FinacialAccountStockOut(myUID, myRow.Cells[newSoIDColumn.Name].Value.ToString());
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }

                    var myTable = newStockOutDataGridView.DataSource as PipeAutoDataSet.VisualStockOutDocsDataTable;

                    foreach (var myRes in myTable)
                    {
                        if (myRes.ID == myRow.Cells[newSoIDColumn.Name].Value.ToString())
                        {
                            myTable.Rows.Remove(myRes);
                            i--;
                            break;
                        }
                    }
                }
            }

            

            MessageBox.Show("成功！");
        }

        private void soFinancialCancelToolStripButton_Click(object sender, EventArgs e)
        {
            int mySelected = 0;

            try
            {
                mySelected = validateChecked(soSearchDataGridView, soSeaChkColumn.Name);

                if (MessageBox.Show("即将弃审，是否继续？", confirmCaption, MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }

                for (int i = 0; i < soSearchDataGridView.Rows.Count; i++)
                {
                    if (mySelected == 0)
                    {
                        break;
                    }

                    var myRow = soSearchDataGridView.Rows[i];


                    if (myRow.Cells[soSeaChkColumn.Name].Value != null && bool.Parse(myRow.Cells[soSeaChkColumn.Name].Value.ToString()) == true)
                    {
                        mySelected--;

                        var myDocId = myRow.Cells[soSeaIDColumn.Name].Value.ToString();

                        var myTable = soSearchDataGridView.DataSource as PipeAutoDataSet.VisualStockOutDocsDataTable;

                        foreach (var myDataRow in myTable)
                        {
                            if (myDataRow.ID==myDocId)
                            {
                                //not the right state
                                if (myDataRow.State!=2)
                                {
                                    throw new MsgBoxException("只有审核状态的出库单才可以弃审！", MgrPlatformGlobal.ExceptionCaption);
                                }

                                //finacial deaccount
                                var mySoDocAdapter = new VisualStockOutDocsTableAdapter();
                                mySoDocAdapter.FinacialDeAccountStockOut(myDataRow.ID);

                                //need del from grid view
                                if (soStateTitledComboBox.Checked==true)
                                {
                                    myTable.Rows.Remove(myDataRow);
                                    i--;
                                }
                                //change state
                                else
                                {
                                    myDataRow.State = 1;
                                    myTable.StateNameColumn.ReadOnly = false;
                                    myDataRow.StateName = MgrPlatformGlobal.GetStockOutStat(1);
                                    myTable.StateNameColumn.ReadOnly = true;
                                }

                                break;
                            }
                        }

                    }


                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, MgrPlatformGlobal.ExceptionCaption);
                return;
            }




            MessageBox.Show("成功！");
        }

        private const string transStockOutDocFile = "transstockoutdocs.xml";
        private const string transStockOutRecFile = "transstockoutrecs.xml";
        private const string stockOutRecDetailFile = "stockoutrecdetail.xml";

        private void soSendToolStripButton_Click(object sender, EventArgs e)
        {
            int mySelected = 0;
            try
            {
                mySelected = validateChecked(soSearchDataGridView,soSeaChkColumn.Name);
            }
            catch(MsgBoxException)
            {
                if (MessageBox.Show("您没有勾选出库记录，本次只传输基础数据，不传输出库单，是否继续？",confirmCaption,MessageBoxButtons.YesNo)!=DialogResult.Yes)
                {
                    return;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            var myTransDir = Properties.Settings.Default.StockOutsTranslateDir;
            //ensure directory exist
            if (Directory.Exists(myTransDir) == false)
            {
                Directory.CreateDirectory(myTransDir);
            }

            //data table for translate stock out document
            var myTransSoDocTable = new PipeAutoDataSet.StockOutDocsDataTable();

            var myTransSoRecTable = new PipeAutoDataSet.TransStockOutRecsDataTable();

            bool needTransSo = mySelected == 0 ? false : true;

            var mySoDocTable = soSearchDataGridView.DataSource as PipeAutoDataSet.VisualStockOutDocsDataTable;


            var mySoDocAdapter = new StockOutDocsTableAdapter();
            var mySoRecAdpater = new TransStockOutRecsTableAdapter();

            //generate stock out data table
            for (int i = 0; i < soSearchDataGridView.Rows.Count; i++)
            {
                if (mySelected == 0)
                {
                    break;
                }

                var myRow = soSearchDataGridView.Rows[i];



                //checked
                if (myRow.Cells[soSeaChkColumn.Name].Value != null && bool.Parse(myRow.Cells[soSeaChkColumn.Name].Value.ToString()) == true)
                {
                    mySelected--;


                    //state wrong
                    if (myRow.Cells[soSeaStateColumn.Name].Value.ToString() != MgrPlatformGlobal.GetStockOutStat(2))
                    {
                        //has translated
                        if (myRow.Cells[soSeaStateColumn.Name].Value.ToString() == MgrPlatformGlobal.GetStockOutStat(6))
                        {
                            if (MessageBox.Show("申请单号为"+myRow.Cells[soSeaIDColumn.Name].Value.ToString()+"的申请单已经传输，是否再次传输？",confirmCaption,MessageBoxButtons.YesNo)!=DialogResult.Yes)
                            {
                                return;
                            }
                        }
                        else
                        {


                            MessageBox.Show("只有审核状态的出库单才可以传送到PDA！");
                            return;
                        }
                    }


#if !DEBUG
                    try
                    {
#endif

                    var mySoDocID=myRow.Cells[soSeaIDColumn.Name].Value.ToString();

                    //get stock out documents data
                    var mySOTable = mySoDocAdapter.GetDataByID(mySoDocID);

                    //import to translation table
                    myTransSoDocTable.ImportRow(mySOTable[0]);

                    //process stock out records
                    var mySoRecTable = mySoRecAdpater.GetDataByDocID(mySoDocID);

                    foreach (var mySoRecRow in mySoRecTable)
                    {
                        myTransSoRecTable.ImportRow(mySoRecRow);
                    }
#if !DEBUG
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }
#endif
                }
            }

            

            myTransSoDocTable.WriteXml(myTransDir + "//"+transStockOutDocFile);

            myTransSoRecTable.WriteXml(myTransDir + "//"+transStockOutRecFile);


            //generate users information
            TransUsersTableAdapter myTransUsersAdapter = new TransUsersTableAdapter();

            var myTransUsersTable = myTransUsersAdapter.GetData(1);

            myTransUsersTable.WriteXml(myTransDir + "//users.xml");

            //generate bar code elements files
            BarcodeElementDicTableAdapter myBarCodeAdapter = new BarcodeElementDicTableAdapter();

            //category elements
            var myCateTable = myBarCodeAdapter.GetDataByTypeState(1, 1);
            myCateTable.WriteXml(myTransDir + "//cateele.xml");

            //trademark elements
            var myTradeEle = myBarCodeAdapter.GetDataByTypeState(2, 1);
            myTradeEle.WriteXml(myTransDir + "//tradeele.xml");

            //partial number elements
            var myPnEle = myBarCodeAdapter.GetDataByTypeState(3, 1);
            myPnEle.WriteXml(myTransDir + "//pnele.xml");

            //color elements
            var myColorEle = myBarCodeAdapter.GetDataByTypeState(4, 1);
            myColorEle.WriteXml(myTransDir + "//colorele.xml");

            //custom information
            var myCusAdapter = new CustomInfoTableAdapter();
            var myCusInfo = myCusAdapter.GetTransData();
            myCusInfo.WriteXml(myTransDir + "//custominfo.xml");

            if (MessageBox.Show("PDA是否已经连接到电脑？", confirmCaption, MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            string remoteDir = Properties.Settings.Default.PDATransDir;

            using (RAPI myRapi = new RAPI())
            {
#if !DEBUG
                try
                {
#endif
                myRapi.Connect(false, -1);

                if (myRapi.DevicePresent == false)
                {
                    MessageBox.Show("请先确保PDA和电脑连接正常，然后重新传输！", "传输失败");
                    return;
                }



                //translate stock out information
                if (myRapi.DeviceFileExists(remoteDir + "//"+transStockOutDocFile) == true)
                {
                    if (Properties.Settings.Default.PromptBeforeDelete == true)
                    {
                        if (MessageBox.Show("PDA中还有上次出库信息，即将删除这些信息，是否继续", confirmCaption, MessageBoxButtons.YesNo) != DialogResult.Yes)
                        {
                            return;
                        }

                        if (myRapi.DeviceFileExists(remoteDir + "//"+stockOutRecDetailFile)==true)
                        {

                            myRapi.DeleteDeviceFile(remoteDir + "//"+stockOutRecDetailFile);
                        }
                    }

                }
                else
                {
                    try
                    {
                        myRapi.CreateDeviceDirectory(remoteDir);
                    }
                    catch (RAPIException)
                    {

                    }
                }

                //need translate stock out data
                if (needTransSo==true)
                {
                    copyFile2Dev(transStockOutDocFile, myRapi);

                    

                    //update stock out document state
                    foreach (var mySoDocRow in myTransSoDocTable)
                    {
                        //update db
                        mySoDocAdapter.UpdateState(6, mySoDocRow.ID);

                        
                        //update visual
                        foreach (var myGridSoDocRow in mySoDocTable)
                        {
                            if (myGridSoDocRow.ID==mySoDocRow.ID)
                            {
                                mySoDocTable.StateColumn.ReadOnly = false;
                                mySoDocTable.StateNameColumn.ReadOnly = false;

                                myGridSoDocRow.State = 6;
                                myGridSoDocRow.StateName = MgrPlatformGlobal.GetStockOutStat(6);

                                mySoDocTable.StateColumn.ReadOnly = true;
                                mySoDocTable.StateNameColumn.ReadOnly = true;

                                break;
                            }
                        }

                        
                    }

                    

                    copyFile2Dev(transStockOutRecFile, myRapi);
                }



                //translate users information
                copyFile2Dev("users.xml", myRapi);

                //translate barcode elements to pda
                copyFile2Dev("cateele.xml", myRapi);
                copyFile2Dev("tradeele.xml", myRapi);
                copyFile2Dev("pnele.xml", myRapi);
                copyFile2Dev("colorele.xml", myRapi);

                //translate custom info
                copyFile2Dev("custominfo.xml", myRapi);






#if !DEBUG
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
#endif
            }

            MessageBox.Show("成功！");
        }

        /// <summary>
        /// copy file to device
        /// </summary>
        /// <param name="fileName">file name</param>
        /// <param name="transProtocal"></param>
        private void copyFile2Dev(string fileName,RAPI transProtocal)
        {
            //data file's source path in pc
            string sourcPath = Properties.Settings.Default.StockOutsTranslateDir+"//"+fileName;

            //destiny path in pda
            string destinyPath = Properties.Settings.Default.PDATransDir+"//"+fileName;

            //validate file
            if (transProtocal.DeviceFileExists(destinyPath)==true)
            {
                transProtocal.DeleteDeviceFile(destinyPath);
            }

            //translate file to pda
            transProtocal.CopyFileToDevice(sourcPath, destinyPath);
        }

        private void soAutoToolStripButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("PDA是否已经连接到电脑？", confirmCaption, MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }


#if !DEBUG

            try
            {
#endif
                RAPI myRapi = new RAPI();

                myRapi.Connect(false, -1);

                if (myRapi.DevicePresent == false)
                {
                    MessageBox.Show("请先确保PDA和电脑连接正常，然后重试！", "自动出库失败");
                    return;
                }

                if (Directory.Exists(Properties.Settings.Default.AutoStockOutDir) == false)
                {
                    Directory.CreateDirectory(Properties.Settings.Default.AutoStockOutDir);
                }

                string myTransDir = Properties.Settings.Default.AutoStockOutDir;

                //need archive in local
                if (Properties.Settings.Default.DeleteAfterTrans == true)
                {
                    DataBaseDateTableAdapter myDBAdapter = new DataBaseDateTableAdapter();
                    var myDBTable = myDBAdapter.GetData();

                    var myDBTime = myDBTable[0].DBDate;

                    myTransDir = myTransDir + "//" + myDBTime.Date.ToShortDateString() + " " + myDBTime.Hour.ToString() + "_" + myDBTime.Minute.ToString() + "_" + myDBTime.Second.ToString() + "_" + myDBTime.Millisecond.ToString();

                    Directory.CreateDirectory(myTransDir);
                }



                //translate stock out
                CopyFile2PC(transStockOutDocFile, myRapi, myTransDir);
                CopyFile2PC(transStockOutRecFile, myRapi, myTransDir);

                //translate stock out detail
                CopyFile2PC(stockOutRecDetailFile, myRapi, myTransDir);

                myRapi.Disconnect();
                myRapi.Dispose();

                MessageBox.Show("数据文件已经传输到本地，可以拔出PDA");

                var myIdentity=Thread.CurrentPrincipal.Identity as WinformIdentity;

                //load stock out doc
                var myRcvSoDoc = new PipeAutoDataSet.StockOutDocsDataTable();
                myRcvSoDoc.ReadXml(myTransDir + "//" + transStockOutDocFile);
                //myRcvSoDoc.AcceptChanges();

                var myNewGreenChannelDoc = new PipeAutoDataSet.StockOutDocsDataTable();

                //add green channel stock out doc into db
                foreach (var myRcvSoDocRow in myRcvSoDoc)
                {
                    //is green channel
                    if (myRcvSoDocRow.StockOutMethod==2)
                    {
                        myRcvSoDocRow.State = 1;
                        myNewGreenChannelDoc.ImportRow(myRcvSoDocRow);
                    }
                }

                //get added green channel
                var myGreenChannelDocsChanges = myNewGreenChannelDoc.GetChanges() as PipeAutoDataSet.StockOutDocsDataTable;

            //has green channel
                if (myGreenChannelDocsChanges != null)
                {


                    var mySoDocAdapter = new StockOutDocsTableAdapter();

                    //add to db
                    mySoDocAdapter.Update(myGreenChannelDocsChanges);

                    //load stock out recs
                    var myRcvSoRecs = new PipeAutoDataSet.TransStockOutRecsDataTable();
                    myRcvSoRecs.ReadXml(myTransDir + "//" + transStockOutRecFile);
                    //myRcvSoRecs.AcceptChanges();

                    var myNewGreenChannelRecs = new PipeAutoDataSet.TransStockOutRecsDataTable();

                    foreach (var myRcvSoRecRow in myRcvSoRecs)
                    {
                        bool isInGreenChannel = false;

                        //whether is newly added green channel records
                        foreach (var myAddGreenChannelDoc in myGreenChannelDocsChanges)
                        {
                            if (myAddGreenChannelDoc.ID == myRcvSoRecRow.DocID)
                            {
                                isInGreenChannel = true;
                                break;
                            }
                        }

                        //need to add to db
                        if (isInGreenChannel == true)
                        {
                            myNewGreenChannelRecs.ImportRow(myRcvSoRecRow);
                        }

                    }

                    var myGreenChannelRecsChanges = myNewGreenChannelRecs.GetChanges() as PipeAutoDataSet.TransStockOutRecsDataTable;

                    //has green channel records
                    if (myGreenChannelRecsChanges!=null)
                    {
                        var myRcvRecAdapter = new TransStockOutRecsTableAdapter();
                        myRcvRecAdapter.Update(myGreenChannelRecsChanges);
                    }
                }

                //load stock out rec detail
                var myRcvRecDetailTable = new PipeAutoDataSet.StockOutRecDetailDataTable();
                myRcvRecDetailTable.ReadXml(myTransDir + "//" + stockOutRecDetailFile);

                var myRecDetailLogAdapter = new StockOutRecDetailLogTableAdapter();

                var myAddedRecDetailLogTable = new  PipeAutoDataSet.StockOutRecDetailLogDataTable();


                //add to log
                foreach (var myRcvRecRow in myRcvRecDetailTable)
                {

                    var myAddedRecDetailLogRow = myAddedRecDetailLogTable.NewStockOutRecDetailLogRow();
                    myAddedRecDetailLogRow.ID = Guid.NewGuid().ToString();
                    myAddedRecDetailLogRow.BarCode = myRcvRecRow.BarCode;
                    myAddedRecDetailLogRow.CateCode = myRcvRecRow.CateCode;
                    myAddedRecDetailLogRow.TradeCode = myRcvRecRow.TradeCode;
                    myAddedRecDetailLogRow.PnCode = myRcvRecRow.PnCode;
                    myAddedRecDetailLogRow.ColorCode = myRcvRecRow.ColorCode;
                    myAddedRecDetailLogRow.StockOutRecID = myRcvRecRow.StockOutRecID;
                    myAddedRecDetailLogRow.StockOutUser = myRcvRecRow.StockOutUser;
                    myAddedRecDetailLogRow.StockOutTime = myRcvRecRow.StockOutTime;
                    myAddedRecDetailLogRow.CreateUser = myIdentity.ID;
                    myAddedRecDetailLogRow.State = 1;

                    myAddedRecDetailLogTable.AddStockOutRecDetailLogRow(myAddedRecDetailLogRow);
                }

                var myChangedRecDetailLogTable = myAddedRecDetailLogTable.GetChanges() as PipeAutoDataSet.StockOutRecDetailLogDataTable;

            //update to db
                myRecDetailLogAdapter.Update(myChangedRecDetailLogTable);
                myAddedRecDetailLogTable.AcceptChanges();

                var mySoRecDetailAdapter = new StockOutRecDetailTableAdapter();
                var myStockInAdapter = new StockInsTableAdapter();
                var myStockAdpater=new StockTableAdapter();

                int mySoAddSiCount = 0;
                int myErrorCount = 0;

            //whether stock out add stock in when not found stock in
                bool stockOutAddStockInFlage=bool.Parse(MgrPlatformGlobal.MgrConfiguration["stockoutaddstockin"].ToString());
                bool interruptAutoStockOutOnError = bool.Parse(MgrPlatformGlobal.MgrConfiguration["interruptautostockoutonerror"].ToString());


            //prerequisite check and auto stock out
                foreach (var myRecDetailLogRow in myAddedRecDetailLogTable)
                {
                    //redundant data in stock out record detail table
                    if (mySoRecDetailAdapter.ScalarByBarCode(myRecDetailLogRow.BarCode)>0)
                    {
                        if (interruptAutoStockOutOnError==true)
                        {
                            throw new Exception("条码号为“" + myRecDetailLogRow.BarCode + "”的产品重复入库！");
                        }
                        //add count
                        myErrorCount++;

                        //update log state
                        myRecDetailLogRow.State = 2;

                        //not need to process this stock out
                        continue;
                    }

                    //not allow to stock in
                    var myRecStorage=myStockAdpater.GetDataByCombo(myRecDetailLogRow.CateCode,
                        myRecDetailLogRow.TradeCode,
                        myRecDetailLogRow.PnCode,
                        myRecDetailLogRow.ColorCode);

                    if (myRecStorage.Count==0)
                    {
                        if (interruptAutoStockOutOnError == true)
                        {
                            throw new Exception("找不到条码为:“" + myRecDetailLogRow.BarCode + "”的产品所对应的库存！");
                        }

                        myErrorCount++;

                        myRecDetailLogRow.State = 3;
                        continue;
                    }
                    else
                    {
                        //insufficient storage and do not add stock in
                        if (myRecStorage[0].LastStock == 0 && stockOutAddStockInFlage == false)
                        {
                            if (interruptAutoStockOutOnError == true)
                            {
                                throw new Exception("条码号为：“" + myRecDetailLogRow.BarCode + "”的产品所对应的库存不足！");
                            }

                            myErrorCount++;

                            myRecDetailLogRow.State = 4;
                            continue;
                        }
                    }

                    var myStockInTable = myStockInAdapter.GetDataByBarCode(myRecDetailLogRow.BarCode);

                    //have not stock in
                    if (myStockInTable.Count==0)
                    {
                        //auto add stock in
                        if (stockOutAddStockInFlage == true)
                        {
                            mySoAddSiCount++;
                            myStockAdpater.StockInTransaction(myRecDetailLogRow.BarCode, myIdentity.ID, 2);
                        }
                        else
                        {
                            if (interruptAutoStockOutOnError == true)
                            {
                                throw new Exception("条码为:“" + myRecDetailLogRow.BarCode + "”的产品找不到入库记录，请检查！");
                            }
                            myErrorCount++;

                            myRecDetailLogRow.State = 5;
                            continue;
                        }
                    }
                        //has stock in 
                    else
                    {
                        //has already stocked out
                        if (myStockInTable[0].State==2)
                        {
                            if (interruptAutoStockOutOnError==true)
                            {
                                throw new Exception("条码为：“" + myRecDetailLogRow.BarCode + "”的产品已经出库（非自动出库）！");
                            }
                            myErrorCount++;

                            myRecDetailLogRow.State = 6;
                            continue;
                        }
                    }

                    //no error occur
                    myStockAdpater.AutoStockOutTransaction(myRecDetailLogRow.BarCode,
                        myRecDetailLogRow.StockOutRecID,
                        myRecDetailLogRow.StockOutUser,
                        myRecDetailLogRow.StockOutTime,
                        myIdentity.ID,
                        myRecDetailLogRow.ID);

                }

            //update logs
                var myPreReqSoLog = myAddedRecDetailLogTable.GetChanges() as PipeAutoDataSet.StockOutRecDetailLogDataTable;

                myRecDetailLogAdapter.Update(myPreReqSoLog);

            //has error
            if (myErrorCount>0)
            {
                //need to prompr user at last
                if (interruptAutoStockOutOnError==true)
                {
                    MessageBox.Show("本次出库过程出现问题，其中错误记录" + myErrorCount + "条！");
                }
            }




            /*string myMsg = "出库处理成功，本次处理出库单：\n" +
                "\n总共单据："+myTotal.ToString()+
                "\n完成：    " + myCompleteCount.ToString() +
                "\n部分完成：" + myUnCompleteCount.ToString() +
                "\n跳过：    " + (myTotal-myCompleteCount-myUnCompleteCount).ToString();

            MessageBox.Show(myMsg, "提示"); */


#if !DEBUG
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
#endif

        }

        private void CopyFile2PC(string fileName, RAPI transProtocal,string destinyDir)
        {
            string sourcePath = Properties.Settings.Default.PDATransDir + "//" + fileName;
            if (transProtocal.DeviceFileExists(sourcePath)==false)
            {
                throw new Exception("出库信息不完整！");
            }

            transProtocal.CopyFileFromDevice(destinyDir + "//" + fileName, sourcePath, true);

            if (Properties.Settings.Default.DeleteAfterTrans==true)
            {
                transProtocal.DeleteDeviceFile(sourcePath);
            }
        }

        private void eleTitleTextBox_Leave(object sender, EventArgs e)
        {
            //title not changed
            if (opState== MgrPlatformGlobal.OperationState.Update&&eleTitleTextBox.Text==barcodeEleToolBtnListViewer.SelectedItems[0].Text&&elePyCodeTextBox.Text==barcodeEleToolBtnListViewer.SelectedItems[0].SubItems["pycode"].Tag.ToString())
            {
                return;
            }
            string myPyCode = string.Empty;

            try
            {
                UtiGlobal.GetFirstPinyinCodes(eleTitleTextBox.Text, ref myPyCode);
                elePyCodeTextBox.Text = myPyCode;
            }
            catch (System.Exception ex)
            {
                elePyCodeTextBox.Text = myPyCode;
                MessageBox.Show(ex.Message);
                return;
            }

            
        }

        private void mgrTabControl_ControlAdded(object sender, ControlEventArgs e)
        {
            
        }

        private void newStockOutDataGridView_DoubleClick(object sender, EventArgs e)
        {
            
        }

        private void newStockOutDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void soSearchDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            var myDatagridView = sender as DataGridView;

            if (myDatagridView==null)
            {
                return;
            }

            //column cell
            if (e.RowIndex<0)
            {
                return;
            }

            if (myDatagridView.SelectedRows.Count==0)
            {
                return;
            }

            string myDocID = string.Empty;

            if (myDatagridView==newStockOutDataGridView)
            {
                myDocID = newStockOutDataGridView.SelectedRows[0].Cells["newsoidcolumn"].Value.ToString();
            }

            if (myDatagridView==soSearchDataGridView)
            {
                myDocID = soSearchDataGridView.SelectedRows[0].Cells["soseaidcolumn"].Value.ToString();
            }

            if (myDocID==string.Empty)
            {
                MessageBox.Show("没有找到出库单信息！");
                return;
            }

            StockOutForm myForm = new StockOutForm();
            myForm.OpState = MgrPlatformGlobal.OperationState.Null;
            myForm.StockOutDocID = myDocID;

            myForm.ShowDialog(this);
        }


     


    }
}
